package com.forlove.app.qselect.answer.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.AppCompatImageView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.forlove.app.R;
import com.forlove.app.common.base.event.BaseMessageEvent;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.NetworkUtils;
import com.forlove.app.common.utils.RandomDataUtil;
import com.forlove.app.common.utils.StatusBarCompat;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.utils.SystemUtils;
import com.forlove.app.manager.EventManager;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.ServerManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.manager.async.LoadContactsAsync;
import com.forlove.app.manager.shotter.ShotterManager;
import com.forlove.app.qselect.CommonEntity;
import com.forlove.app.qselect.MainActivity;
import com.forlove.app.qselect.answer.entity.AnswerEntity;
import com.forlove.app.qselect.answer.entity.AnswerResultEntity;
import com.forlove.app.qselect.answer.entity.BatchInfoEntity;
import com.forlove.app.qselect.answer.entity.LastRecordEntity;
import com.forlove.app.qselect.answer.entity.MsgInfoEntity;
import com.forlove.app.qselect.answer.entity.SubjectsEntity;
import com.forlove.app.qselect.answer.presenter.AnswerSubjectPresenter;
import com.forlove.app.qselect.answer.view.AnswerSubjectView;
import com.forlove.app.qselect.answer.widght.AnswerFriendVew;
import com.forlove.app.qselect.answer.widght.ShareAnswerDetailDialog;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.friend.widget.dialog.SetNewCandidateDialog;
import com.forlove.app.qselect.index.entity.FriendCircleInfoEntity;
import com.forlove.app.qselect.index.ui.IndexFragment;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * 答题页面
 * <p>
 * version 0.3
 * 答题的选人逻辑改为从接口字段取recomand和subject_recomand合并
 * 如果题目有推荐的候选人号码从这两个字段中取出该好友优先显示
 * 其他逻辑不变，原先合并好友和通讯录改到自定义候选人时使用
 * <p>
 * 答题时的圈选人从候选人与subject_recomand合并随机，
 * 目前上限人数不限制，由接口返回
 * <p>
 * version 1.03
 * 添加gif配图
 * Created by yjl on 2017/11/1.
 */

@RuntimePermissions
public class AnswerSubjectActivity extends BaseActivity<AnswerSubjectPresenter> implements AnswerSubjectView,
        LoaderManager.LoaderCallbacks<List<ContactsInfoEntity>>,
        AnswerFriendVew.OnSelectedItemListener,
        View.OnClickListener {

    @BindView(R.id.view_circle_friend)
    AnswerFriendVew view_circle_friend;//答题圈选的好友界面部分

    @BindView(R.id.text_emoji)
    TextView text_emoji;  //图片

    @BindView(R.id.text_change_question)
    TextView text_change_question;  //换题

    @BindView(R.id.view_circle_title)
    TextView view_circle_title;//标题

    @BindView(R.id.view_home)
    FrameLayout view_home;//返回home

    @BindView(R.id.image_back)
    ImageView image_back; //返回图片

    @BindView(R.id.view_answer)
    LinearLayout view_answer;  //页面rootView

    @BindView(R.id.text_answer_progress)
    TextView text_answer_progress;//答题进度

    @BindView(R.id.image_question)
    AppCompatImageView image_question;  //题目的配图

    @BindView(R.id.view_question_image)
    RelativeLayout view_question_image;//配图的view

    @BindView(R.id.text_question)
    TextView text_question;   //出题的文字内容

    @BindView(R.id.text_hot_num)
    TextView text_hot_num;//被点赞数

    @BindView(R.id.view_hot)
    LinearLayout view_hot;//
    @BindView(R.id.text_next_question)
    TextView text_next_question;//下一题

    @BindView(R.id.view_change_question)
    LinearLayout view_change_question;//换题

    @BindView(R.id.view_change_friends)
    LinearLayout view_change_friends; //更换好友

    @BindView(R.id.view_answer_change)
    RelativeLayout view_answer_change;//答题时底部

    @BindView(R.id.view_detail_lock)
    RelativeLayout view_detail_lock;//被圈详情页的底部提示

    @BindView(R.id.view_is_private)
    FrameLayout view_is_private; //是否设置隐私模式

    @BindView(R.id.image_is_private)
    ImageView image_is_private;//设置隐私图片

    @BindView(R.id.view_back)
    View view_back; //背景色部分

    @BindView(R.id.text_friend_not_look)
    TextView text_friend_not_look; //好友不可见试图

    @BindView(R.id.view_select_candidate)
    FrameLayout view_select_candidate; //自定义候选人引出图标

    @BindView(R.id.gif_subject)
    SimpleDraweeView gif_subject; //gif 配图

    @BindView(R.id.text_answer_share)
    TextView text_answer_share;//答题过程中的分享


    private LoadContactsAsync loadContactsAsync;
    private List<ContactsInfoEntity> contactsInfoEntities = new ArrayList<>();//本地手机通讯录好友
    private List<SubjectsEntity> subjectsEntities = new ArrayList<>();//答题的题目信息
    private List<MineFriendEntity> recommendFriend = new ArrayList<>(); //答题接口返回的推荐的好友,候选人列表
    private List<MineFriendEntity> friendEntities = new ArrayList<>(); //通讯录备选的所有好友，筛选过后的所有好友,答题的好友在此列表随机选
    private List<MineFriendEntity> qyqFriendList = new ArrayList<>();//圈一圈好友
    private List<MineFriendEntity> subjectRecommend = new ArrayList<>();//题目推荐的优先显示好友
    private String mColor = "#2ac2b9";
    private AnswerEntity answerEntity;//获取到的题目资源
    private UserEntity userEntity; //用户信息
    private int mSubjectProgess = 0;//答题的序号从0开始
    private int subjectSize = 0;//题目的数目
    private BatchInfoEntity batchInfoEntity;//当前答题批次相关信息
    private LastRecordEntity lastRecordEntity;//最后一次答题信息
    private long mExpire = 0;//  限制答题时间
    private int unlockcost = -1;//解锁答题数目
    private int note_type; //1答题，0跳过
    private boolean canAnswer = false;//能否答题
    private int chioicePos = 0;
    private FriendCircleInfoEntity friendCircleInfoEntity; //个人圈有信息的
    private int mType = -1;//从我的魅力item点击进入
    private int recordId;
    private long clickTime = 0;
    private int maxNum = -1; //默认最多候选人,-1时只是合并
    private boolean recommendFlag = false;//获取到推荐好友，答题接口返回
    private boolean qyqFriendFlag = false;//获取到圈一圈好友的标志
    private boolean contactsFlag = false;//获取到通讯录好友标记
    //    private int changeFriendNum = 0;//换题次数
    private SetNewCandidateDialog setCandidateDialog;
    private Handler cacheHandler;
    private boolean showCandidate = true;
    private ShareAnswerDetailDialog shareAnswerDetailDialog;
    private Bitmap shotBitmap; //截图的bitmap
    private String shotUrl; //截图的保存路径
    private SubjectsEntity subjectsEntity;

    @Override
    public int getLayoutId() {
        return R.layout.activity_answer_subject;
    }

    @NeedsPermission(Manifest.permission.READ_CONTACTS)
    void needContacts() {
        //获取到了通讯录权限
//        Toast.makeText(this, "获取到了通讯录权限", Toast.LENGTH_SHORT).show();
        getSupportLoaderManager().restartLoader(LoadContactsAsync.ASYNC_ID, null, this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AnswerSubjectActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied(Manifest.permission.READ_CONTACTS)
    void getContactsFail() {
        //获取权限失败
        Toast.makeText(this, "通讯录权限被拒绝", Toast.LENGTH_SHORT).show();
        contactsFlag = true;
        loadFriends();
    }

    @OnNeverAskAgain(Manifest.permission.READ_CONTACTS)
    void getContactsAvaliable() {
        //获取权限拒绝不再显示
        Toast.makeText(this, "通讯录权限被拒绝", Toast.LENGTH_SHORT).show();
        contactsFlag = true;
        loadFriends();
    }

    @Override
    public void initView() {
        if (NetworkUtils.instance(this).isNetworkAvailable()) {
            initPageView();
            initData();
        } else {
            Toast.makeText(this, "请检查网络！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }


    private void initData() {
        if (presenter == null) {
            presenter = new AnswerSubjectPresenter(this);
        }

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            friendCircleInfoEntity = (FriendCircleInfoEntity) bundle.getSerializable("friendCircleInfoEntity");
            mType = bundle.getInt("type");
            String answer = (String) bundle.getSerializable("answer");
            if (!TextUtils.isEmpty(answer)) {
                answerEntity = new AnswerEntity();
                answerEntity.parseJSONString(answer);
                setData(answerEntity);
            }
        }
//        loadQyqFriend();
        userEntity = UserManager.getUesrInfo(this);
        if (mType > 0 && friendCircleInfoEntity != null) {
            recordId = friendCircleInfoEntity.recordId;
            view_answer_change.setVisibility(View.GONE);
            view_detail_lock.setVisibility(View.VISIBLE);
            initDetailView();
            //获取详情
            showCandidate = false;
            view_select_candidate.setVisibility(View.INVISIBLE);
            presenter.loadDetailInfoData(friendCircleInfoEntity.recordId, mType);
        } else {
            view_answer_change.setVisibility(View.VISIBLE);
            view_detail_lock.setVisibility(View.GONE);
            view_select_candidate.setVisibility(View.VISIBLE);
            showTitle(batchInfoEntity);
            presenter.loadQuestionData();
            presenter.loadFriendListData();
            showSubjectView();
            if (contactsInfoEntities.size() <= 0) {
                //加载通讯录数据
                AnswerSubjectActivityPermissionsDispatcher.needContactsWithPermissionCheck(AnswerSubjectActivity.this);
            }
        }
    }

    private void initCache() {
        if (cacheHandler == null) {
            cacheHandler = new Handler(getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    return false;
                }
            });
        }
    }

//    private void loadQyqFriend() {
//        if (mType < 0) {
//            HandlerThread handlerThread = new HandlerThread("loadQyqFriend");
//            handlerThread.start();
//            Handler loadHandler = new Handler(handlerThread.getLooper());
//            loadHandler.post(new Runnable() {
//                @Override
//                public void run() {
//                    if (qyqFriendList.size() <= 0) {
//                        String friendList = FriendManager.getFriendList(AnswerSubjectActivity.this);
//                        try {
//                            if (StringUtils.isNotEmpty(friendList)) {
//                                List<MineFriendEntity> friends =
//                                        ParseHelper.getModelList(friendList, "data.friends", FriendEntity.class);
//                                List<MineFriendEntity> contacts =
//                                        ParseHelper.getModelList(friendList, "data.concats", FriendEntity.class);
//                                List<MineFriendEntity> entities = FriendManager.mergeFriends(friends, contacts, -1);
//                                if (entities.size() > 0) {
//                                    qyqFriendList.addAll(entities);
//                                    qyqFriendFlag = true;
//                                }
//                                presenter.loadFriendListData();
//                            }
//                        } catch (Exception e) {
//                        }
//                    }
//                }
//
//            });
//        }
//    }

    private void setData(AnswerEntity entity) {
        subjectSize = entity.subjects.size();
        batchInfoEntity = entity.batchInfo;
        if (batchInfoEntity != null) {
            showProgress(mSubjectProgess);
        }
        //最后一次答题记录
        lastRecordEntity = entity.lastRecordEntity;
        //题目列表
        subjectsEntities.clear();
        subjectsEntities.addAll(entity.subjects);
        //题目推荐好友
        subjectRecommend.clear();
        subjectRecommend.addAll(entity.subjectRecomand);
        //锁题时间
        mExpire = entity.expire;
        //候选人
        recommendFriend.clear();
        recommendFriend.addAll(entity.recomandFriend);
        if (recommendFriend.size() > 0) {
            for (MineFriendEntity friendEntity : recommendFriend) {
                friendEntity.isRecomend = true;
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    //初始化页面元素
    private void initPageView() {
//        view_circle_friend.setOnSelectedItemListener(this);
        view_circle_friend.setAvaliableSelected(false);
        view_change_question.setOnClickListener(this);
        text_next_question.setOnClickListener(this);
        view_change_friends.setOnClickListener(this);
        view_change_question.setOnClickListener(this);
        view_home.setOnClickListener(this);
//        text_select_candidate.setOnClickListener(this);
        view_select_candidate.setOnClickListener(this);
    }

    /**
     * 展示显示答题详情时候的页面
     */
    private void initDetailView() {
        text_answer_progress.setText(friendCircleInfoEntity.info);
        text_question.setText(friendCircleInfoEntity.name);
        view_change_question.setVisibility(View.INVISIBLE);
        text_next_question.setVisibility(View.GONE);
        text_answer_share.setVisibility(View.GONE);
        view_change_friends.setVisibility(View.INVISIBLE);
        if (mType == 1) {
            view_answer_change.setVisibility(View.VISIBLE);
            view_detail_lock.setVisibility(View.GONE);
        } else if (mType == 2) {
            view_answer_change.setVisibility(View.GONE);
            view_detail_lock.setVisibility(View.VISIBLE);
        }
        view_hot.setVisibility(View.INVISIBLE);
        view_circle_title.setText("详情");
        view_is_private.setOnClickListener(this);
        image_back.setBackgroundResource(R.mipmap.ic_back_nor);

    }

    //显示titlbar 部分
    private void showTitle(BatchInfoEntity batchInfoEntity) {

        if (userEntity != null) {
            text_hot_num.setText(userEntity.diamond + "");
        } else {
            if (batchInfoEntity != null) {
                text_hot_num.setText(batchInfoEntity.note_times + "");
            }
        }
        view_circle_title.setText("圈一圈 ");
    }

    //显示 答题进度,序号从0开始
    private void showProgress(int num) {
        String progress = num + 1 + "/" + subjectSize;
        text_answer_progress.setText(progress);
    }

    //展示题目信息
    private void showSubject(SubjectsEntity subjectsEntity) {
        if (subjectsEntity == null) {
            return;
        }
        this.subjectsEntity = subjectsEntity;
        mColor = subjectsEntity.bgColor;
        //显示背景颜色部分
//        StatusBarCompat.compat(this, Color.parseColor(mColor));
//        view_back.setBackgroundColor(Color.parseColor(mColor));
        if (!StringUtils.isNotEmpty(mColor)) {
            mColor = "#2ac2b9";
        }
        view_back.setVisibility(View.INVISIBLE);
        view_answer.setBackgroundColor(Color.parseColor(mColor));

        //显示图片
        if (StringUtils.isNotEmpty(subjectsEntity.path)) {
            showGifOrPNG(subjectsEntity.path);
        } else {
            showContentImag(subjectsEntity.mPic);
        }
        //显示题目内容
        if (!TextUtils.isEmpty(subjectsEntity.name)) {
            text_question.setText(subjectsEntity.name);
            text_question.setVisibility(View.VISIBLE);
        } else {
            text_question.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 换题显示
     */
    private void showSubjectView() {
        if (lastRecordEntity == null || (lastRecordEntity.batch != batchInfoEntity.batch)) {
            //批次不一致则进度从0开始
            mSubjectProgess = 0;
        } else if (lastRecordEntity != null && lastRecordEntity.batch == batchInfoEntity.batch) {
            //同一批次则从index题开始，lastrecord中的index是从1开始
            mSubjectProgess = lastRecordEntity.index;
        }
        showProgress(mSubjectProgess);
        if (mSubjectProgess < subjectsEntities.size() && subjectsEntities.size() > 0) {
            SubjectsEntity subjectsEntity = subjectsEntities.get(mSubjectProgess);
            if (!StringUtils.isNotEmpty(subjectsEntity.bgColor)) {
                subjectsEntity.bgColor = "#2ac2b9";
            }
            StatusBarCompat.compat(this, Color.parseColor(subjectsEntity.bgColor));
            view_back.setBackgroundColor(Color.parseColor(subjectsEntity.bgColor));
            showSubject(subjectsEntity);
        }
    }

    /**
     * 随机取四个通讯录好友
     * 优先会显示候选人列表
     */
    private void changeCircleFriend() {

        if (friendEntities != null && friendEntities.size() >= 4) {
            if (mHandler == null) {
                mHandler = new Handler();
            }
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    List<MineFriendEntity> friends = new ArrayList<>();
                    //TODO 设置候选人优先显示
                    if (friendEntities.size() > 8) {
                        friends.addAll(RandomDataUtil.generateRandomDataNoRepeat(friendEntities, 8));
                    } else {
                        friends.addAll(friendEntities);
                    }

                    List<MineFriendEntity> recfirend = new ArrayList<>();
                    if (recommendFriend.size() > 4) {
                        recfirend.addAll(RandomDataUtil.generateRandomDataNoRepeat(recommendFriend, 4));
                    } else {
                        recfirend.addAll(recommendFriend);
                    }
                    List<MineFriendEntity> entities = new ArrayList<>();
                    entities.addAll(friends);
                    entities.addAll(recfirend);

                    List<MineFriendEntity> showFriend = new ArrayList<>();
                    showFriend.addAll(FriendManager.removeDuplicateFriend(entities));
                    if (showFriend.size() <= 4) {
                        view_circle_friend.updateAnswerFriend(showFriend);
                    } else {
                        view_circle_friend.updateAnswerFriend(RandomDataUtil.generateRandomDataNoRepeat(showFriend, 4));
                    }
                }
            });

        }

    }

    /**
     * 优先显示好友中已经被圈选的人
     * 再填补候选人
     */
    private void getFirstShowFriend(SubjectsEntity subjectsEntity) {
        if (subjectsEntity == null) {
            return;
        }
        List<MineFriendEntity> subjectRec = new ArrayList<>();//当前题目推荐的
        if (StringUtils.isNotEmpty(subjectsEntity.recomand)) {
            String[] recMobile = subjectsEntity.recomand.split(",");
            for (String mobile : recMobile) {
                for (MineFriendEntity mineFriendEntity : friendEntities) {
                    if (mobile.equals(mineFriendEntity.mobile)) {
                        MineFriendEntity entity = new MineFriendEntity(mineFriendEntity);
                        entity.hasCircle = true;
                        subjectRec.add(entity);
                        break;
                    }
                }
            }
        }
        if (subjectRec.size() >= 4) {
            view_circle_friend.updateAnswerFriend(subjectRec);
        } else if (subjectRec.size() > 0 && subjectRec.size() < 4 && friendEntities.size() > 4) {
            subjectRec.addAll(RandomDataUtil.generateRandomDataNoRepeat(friendEntities, 4));
            List<MineFriendEntity> showFriend = new ArrayList<>();
            showFriend.addAll(FriendManager.removeDuplicateFriend(subjectRec));
            if (showFriend.size() > 4) {
                view_circle_friend.updateAnswerFriend(FriendManager.sortCircleNum(showFriend));
            } else {
                view_circle_friend.updateAnswerFriend(showFriend);
            }
        } else {
            changeCircleFriend();
        }

    }

    /**
     * 设置完候选人后的显示圈选项
     */
    private void changeFirendAfterSetCandidate() {
        List<MineFriendEntity> recommends = new ArrayList<>();
        recommends.addAll(recommendFriend);
        friendEntities.clear();
        if (recommends.size() == 0) {
            //如果选择自定义候选人为0 时
            friendEntities.addAll(FriendManager.getSubjectCandidate(recommends, qyqFriendList, contactsInfoEntities, maxNum));
        } else {
            friendEntities.addAll(FriendManager.mergeFriends(recommends, subjectRecommend, maxNum));
        }
        if (recommendFriend.size() == 4) {
            view_circle_friend.updateAnswerFriend(recommendFriend);
        } else if (recommendFriend.size() > 4) {
            List<MineFriendEntity> recfirend = new ArrayList<>();
//            recfirend.addAll(RandomDataUtil.generateRandomDataNoRepeat(recommendFriend, 4));
            recfirend.addAll(recommendFriend.subList(0, 4));
            view_circle_friend.updateAnswerFriend(recfirend);
        } else if (recommendFriend.size() > 0 && recommendFriend.size() < 4 && friendEntities.size() > 4) {
            List<MineFriendEntity> recfirend = new ArrayList<>();
            recfirend.addAll(recommendFriend);
            recfirend.addAll(RandomDataUtil.generateRandomDataNoRepeat(friendEntities, 4));
            List<MineFriendEntity> showFriend = new ArrayList<>();
            showFriend.addAll(FriendManager.removeDuplicateFriend(recfirend));
            view_circle_friend.updateAnswerFriend(FriendManager.sortRecommend(showFriend));
        } else {
            changeCircleFriend();
        }
    }

    /**
     * 显示题目的图片
     */
    private void showContentImag(String image) {
        try {
            if (!TextUtils.isEmpty(image)) {
                if (!image.startsWith("/")) {
                    //显示emoji
                    if (image.contains(".")) {
                        String[] str = image.split("\\.");
                        image = str[0];
                    }
                    if (SystemUtils.getSDKVersion() >= 21) {
                        int emojiInt = Integer.parseInt(image, 16);
                        text_emoji.setText(getEmojiStringByUnicode(emojiInt));
                        text_emoji.setVisibility(View.VISIBLE);
                        image_question.setVisibility(View.INVISIBLE);
                    } else {
                        // 不显示
                        text_emoji.setVisibility(View.INVISIBLE);
                        String url = ServerManager.ImageUrlEmoji + "/" + image.toLowerCase() + ".png";
                        presenter.loadImageView(this, image_question, url, 0);
                        image_question.setVisibility(View.VISIBLE);
                    }

                } else {
                    // 显示图片
                    text_emoji.setVisibility(View.INVISIBLE);
                    presenter.loadImageView(this, text_emoji, image, 0);
                    image_question.setVisibility(View.VISIBLE);
                }
            } else {
                view_question_image.setVisibility(View.GONE);
            }
            gif_subject.setVisibility(View.INVISIBLE);
        } catch (NumberFormatException e) {
            LogUtil.e(e.getMessage());
        } catch (Exception e) {
            LogUtil.e(e.getMessage());
        }
    }

    /**
     * 显示gif或者png,jpg
     *
     * @param path
     */
    private void showGifOrPNG(String path) {
        gif_subject.setVisibility(View.VISIBLE);
        text_emoji.setVisibility(View.INVISIBLE);
        image_question.setVisibility(View.INVISIBLE);
        Uri uri = Uri.parse(ServerManager.getImageUrl() + path);
        DraweeController mDraweeController = Fresco.newDraweeControllerBuilder().setAutoPlayAnimations(true)
                //设置uri,加载本地的gif资源
//                .setUri(Uri.parse("res://" + getPackageName() + "/" + R.mipmap.add_friend_guide))//设置uri
                .setUri(uri)
                .build();
        //设置Controller

        gif_subject.setController(mDraweeController);
    }

    private String getEmojiStringByUnicode(int unicode) {
        return new String(Character.toChars(unicode));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!StringUtils.isNotEmpty(mColor)) {
            mColor = "#2ac2b9";
        }
        StatusBarCompat.compat(this, Color.parseColor(mColor));
        view_answer.setBackgroundColor(Color.parseColor(mColor));
    }

    private LoadContactsAsync createContacts() {
        if (loadContactsAsync == null) {
            loadContactsAsync = new LoadContactsAsync(this);
        }
        return loadContactsAsync;
    }

    @Override
    public Loader<List<ContactsInfoEntity>> onCreateLoader(int id, Bundle args) {
        return createContacts();
    }

    @Override
    public void onLoadFinished(Loader<List<ContactsInfoEntity>> loader, List<ContactsInfoEntity> data) {
        //加载通讯录
        getSupportLoaderManager().destroyLoader(LoadContactsAsync.ASYNC_ID);
        contactsInfoEntities.clear();
        contactsInfoEntities.addAll(data);
        contactsFlag = true;
        loadFriends();
    }

    @Override
    public void onLoaderReset(Loader<List<ContactsInfoEntity>> loader) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getSupportLoaderManager().destroyLoader(LoadContactsAsync.ASYNC_ID);
        if (setCandidateDialog != null) {
            setCandidateDialog.dismiss();
            setCandidateDialog.clearData();
            setCandidateDialog = null;
        }
        if (shareAnswerDetailDialog != null) {
            shareAnswerDetailDialog.dismiss();
            shareAnswerDetailDialog.clearData();
            shareAnswerDetailDialog = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_home:
                if (mType < 0) {
                    toMainActivity(MainActivity.POSITION_INDEX, IndexFragment.POSITION_INDEX_MiNE);
                    finish();
                } else {
                    onBackPressed();
                }
                finish();
                break;
            case R.id.text_next_question:
                //下一题
                showNextSubject();
                view_circle_friend.setOnSelectedItemListener(this);
                view_circle_friend.setAvaliableSelected(true);
                hideNextQuestion();
                break;
            case R.id.view_change_question:
                if (System.currentTimeMillis() - clickTime < 1500) {
                    clickTime = System.currentTimeMillis();
                    return;
                }
                //换题
                //TODO 换题操作有问题，需确定
                if (mSubjectProgess < subjectsEntities.size()) {
                    note_type = 0;
                    SubjectsEntity subjectsEntity = subjectsEntities.get(mSubjectProgess);
                    view_circle_friend.setOnSelectedItemListener(null);
                    view_circle_friend.setAvaliableSelected(false);
                    requestAnswerSubject(subjectsEntity);
                }
                break;
            case R.id.view_change_friends:
                //换好友
                if (friendEntities == null || friendEntities.size() == 0) {
                    Toast.makeText(this, "正在加载好友，请稍后", Toast.LENGTH_SHORT).show();
                    return;
                }
                changeCircleFriend();
                break;
            case R.id.view_is_private:
                presenter.loadDetailLockData(recordId);
                break;
            case R.id.view_select_candidate:
                showSetCandidateDialog();
                break;
        }
    }

    /**
     * 显示自定义候选人dialog
     */
    private void showSetCandidateDialog() {
        // 显示设置候选人
        if (setCandidateDialog == null) {
            setCandidateDialog = new SetNewCandidateDialog();
            setCandidateDialog.setPresenter(presenter);
            setCandidateDialog.setAnswerViewListener(new SetNewCandidateDialog.AnswerViewListener() {
                @Override
                public void answerSubject(List<MineFriendEntity> circleFirend) {
                    MineFriendEntity mineFriendEntity = circleFirend.get(0);
                    //先去重
                    List<MineFriendEntity> mineFriendEntities = new ArrayList<>();
                    mineFriendEntities.addAll(view_circle_friend.getAnswerFriend());
//                    mineFriendEntities.removeAll(circleFirend);
                    for (MineFriendEntity entity : view_circle_friend.getAnswerFriend()) {
                        if (entity.getAvaliableMobile().equals(mineFriendEntity.getAvaliableMobile())) {
                            mineFriendEntities.remove(entity);
                        }
                    }
                    if (mineFriendEntities.size() >= 4) {
                        mineFriendEntities.set(0, mineFriendEntity);
                    } else {
                        mineFriendEntities.add(0, mineFriendEntity);
                    }
                    view_circle_friend.updateAnswerFriend(mineFriendEntities);
                    view_circle_friend.setCircleFriend(0);
                }

                @Override
                public void updateCandidate(List<MineFriendEntity> mineFriendEntities) {

                    if (mineFriendEntities != null) {
                        if (NetworkUtils.instance(AnswerSubjectActivity.this).isNetworkAvailable()) {
                            presenter.loadCondidateFriends(mineFriendEntities);
                            canAnswer = false;
                        } else {
                            Toast.makeText(AnswerSubjectActivity.this, "请检查网络！",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });
        }
        setCandidateDialog.show(getSupportFragmentManager(), "setCandidateDialog");
        setCandidateDialog.setFriendsData(recommendFriend, qyqFriendList, contactsInfoEntities);
    }

    /**
     * 换题
     */
    private void showNextSubject() {
        if (mSubjectProgess < subjectsEntities.size()) {
            SubjectsEntity subjectsEntity = subjectsEntities.get(mSubjectProgess);
            showSubject(subjectsEntity);
            showProgress(mSubjectProgess);
            getFirstShowFriend(subjectsEntity);
            showAnimation();
            //TODO 答题或者跳过题目成功后才自增
        } else if (mSubjectProgess >= subjectsEntities.size() && mExpire != 0) {
            toLimitView(batchInfoEntity);
        }
    }

    private String[] getMobileList(List<MineFriendEntity> circleFirend) {
        StringBuilder mobile_list = new StringBuilder();
        StringBuilder name_list = new StringBuilder();
        //选项会出现大于四的情况，只取前四个人
        for (int i = 0; i < 4; i++) {
            MineFriendEntity contactsInfoEntity = circleFirend.get(i);
            if (i < 3) {
                if (!TextUtils.isEmpty(contactsInfoEntity.contactsNumber)) {
                    mobile_list.append(contactsInfoEntity.contactsNumber).append(",");
                } else {
                    mobile_list.append(contactsInfoEntity.mobile).append(",");
                }
                name_list.append(contactsInfoEntity.getAvaliableName()).append(",");
            } else if (i == 3) {
                if (!TextUtils.isEmpty(contactsInfoEntity.contactsNumber)) {
                    mobile_list.append(contactsInfoEntity.contactsNumber);
                } else {
                    mobile_list.append(contactsInfoEntity.mobile);
                }
                name_list.append(contactsInfoEntity.getAvaliableName());
            }
        }
        String[] str = new String[]{mobile_list.toString(), name_list.toString()};
        return str;
    }

    private void showAnimation() {

        view_back.setVisibility(View.VISIBLE);
        Animator animatorOut = ObjectAnimator.ofFloat(view_back, "translationY",
                0f, -view_back.getHeight());
        Animator animatorIn = ObjectAnimator.ofFloat(view_answer, "alpha", 0.5f, 1f);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(animatorOut, animatorIn);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.setDuration(200);
        animatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                view_back.setVisibility(View.INVISIBLE);
                view_back.setBackgroundColor(Color.parseColor(mColor));
                StatusBarCompat.compat(AnswerSubjectActivity.this, Color.parseColor(mColor));
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                view_back.setVisibility(View.INVISIBLE);
                view_back.setBackgroundColor(Color.parseColor(mColor));
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animatorSet.start();

    }

    private void showSubjectDetail(final MsgInfoEntity msgInfoEntity, SubjectsEntity subjectsEntity) {

        if (subjectsEntity != null) {
            mColor = subjectsEntity.bgColor;
            if (!StringUtils.isNotEmpty(mColor)) {
                mColor = "#2ac2b9";
            }
            StatusBarCompat.compat(this, Color.parseColor(mColor));
            view_back.setBackgroundColor(Color.parseColor(mColor));
            view_back.setVisibility(View.INVISIBLE);
            view_answer.setBackgroundColor(Color.parseColor(mColor));
            //显示图片

            if (StringUtils.isNotEmpty(subjectsEntity.path)) {
                showGifOrPNG(subjectsEntity.path);
            } else {
                String image = subjectsEntity.mPic;
                showContentImag(image);
            }
            String content = subjectsEntity.name;
            if (!TextUtils.isEmpty(content)) {
                text_question.setText(content);
                text_question.setVisibility(View.VISIBLE);
            } else {
                text_question.setVisibility(View.INVISIBLE);
            }
        }
        if (msgInfoEntity != null) {
            if (msgInfoEntity.priva == 0) {
                image_is_private.setBackgroundResource(R.mipmap.icon_subject_unlock);
                ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(text_friend_not_look,
                        "translationY", 0, text_friend_not_look.getHeight());
                objectAnimator.setDuration(200);
                objectAnimator.start();
                objectAnimator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        text_friend_not_look.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                        text_friend_not_look.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                });
            } else if (msgInfoEntity.priva == 1) {
                image_is_private.setBackgroundResource(R.mipmap.icon_subject_lock);
                ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(text_friend_not_look,
                        "translationY", text_friend_not_look.getHeight(), 0);
                objectAnimator.setDuration(200);
                objectAnimator.start();
                text_friend_not_look.setVisibility(View.VISIBLE);
            }
            text_answer_progress.setVisibility(View.VISIBLE);
            text_answer_progress.setText(msgInfoEntity.info);
            String[] strs = msgInfoEntity.name_list.split(",");
            String[] names = new String[]{"", "", "", ""};
            for (int i = 0; i < strs.length; i++) {
                names[i] = strs[i];
            }
            String[] mobilStrs = msgInfoEntity.mobile_list.split(",");
            String[] mobileList = new String[]{"", "", "", ""};
            for (int i = 0; i < mobilStrs.length; i++) {
                mobileList[i] = mobilStrs[i];
            }
            if (!TextUtils.isEmpty(msgInfoEntity.answers)) {
                String[] answers = msgInfoEntity.answers.split(",");
                view_circle_friend.setCircleFriend(names, mobileList, answers, mColor);
            }
            recordId = msgInfoEntity.recordId;
        }
    }

    private void requestAnswerSubject(SubjectsEntity subjectsEntity) {
        if (!NetworkUtils.instance(this).isNetworkAvailable()) {
            Toast.makeText(this, "网络无法连接，请检查网络!",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (!canAnswer) {
            Toast.makeText(this, "正在获取题目，请稍后!",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> param = new HashMap<>();
        param.put("note_type", note_type + "");
        MineFriendEntity selectedFirend = view_circle_friend.getSelectedFirend();
        if (selectedFirend != null) {
            if (!TextUtils.isEmpty(selectedFirend.mobile)) {
                param.put("answers", selectedFirend.mobile);
            } else {
                param.put("answers", selectedFirend.contactsNumber);
            }
        } else {
            param.put("answers", "");
        }
        param.put("group_tag_id", userEntity.group_tag + "");//答题人的
        param.put("subject_id", subjectsEntity.subId + "");
        param.put("batch", batchInfoEntity.batch + "");
        param.put("index", (mSubjectProgess + 1) + "");
        param.put("priva", 0 + "");//priva 隐私 0公开 1 私人可见
        List<MineFriendEntity> circleFirend = view_circle_friend.getAnswerFriend();
        String[] resultList = getMobileList(circleFirend);
        String mobile_list = resultList[0];
        String name_list = resultList[1];

        param.put("mobile_list", mobile_list);
        param.put("name_list", name_list);
        presenter.loadAnswerSubject(param);

    }

    /**
     * 显示下一题按钮
     */
    private void showNextQuestion() {
        showCandidate = false;
        text_next_question.setVisibility(View.VISIBLE);
        text_answer_share.setVisibility(View.VISIBLE);
        view_change_question.setVisibility(View.INVISIBLE);
        view_change_friends.setVisibility(View.INVISIBLE);
        view_select_candidate.setVisibility(View.INVISIBLE);
    }

    /**
     * 隐藏下一题按钮
     */
    private void hideNextQuestion() {
        showCandidate = true;
        text_next_question.setVisibility(View.GONE);
        text_answer_share.setVisibility(View.GONE);
        view_change_question.setVisibility(View.VISIBLE);
        view_change_friends.setVisibility(View.VISIBLE);
        view_select_candidate.setVisibility(View.VISIBLE);
    }

    @Override
    public void selectedFriend(MineFriendEntity friendEntity, boolean selected, int pos) {
        //选择了哪个好友，目前版本是选择了好友就是答题

        if (selected && view_circle_friend.getSelectedFirend() != null) {
            showNextQuestion();
        } else if (view_circle_friend.getSelectedFirend() != null) {
            hideNextQuestion();
        }
        chioicePos = pos;
        //TODO 答题
        if (mSubjectProgess < subjectsEntities.size()) {
            note_type = 1;
            SubjectsEntity subjectsEntity = subjectsEntities.get(mSubjectProgess);
            view_circle_friend.setOnSelectedItemListener(null);
            view_circle_friend.setAvaliableSelected(false);
            requestAnswerSubject(subjectsEntity);
        }
    }

    private void toLimitView(BatchInfoEntity batchInfoEntity) {
        if (answerEntity == null) {
            return;
        }
//        this.mExpire = expire;
        Intent intent = new Intent(this, LimitAnswerActivity.class);
        Bundle bundle = new Bundle();
        bundle.putLong(LimitAnswerActivity.KEY_EXPIRE_TIME, mExpire);
        bundle.putInt(LimitAnswerActivity.KEY_UNLOCK_NUM, unlockcost);
        if (batchInfoEntity != null) {
            bundle.putInt(LimitAnswerActivity.KEY_CIRCLE_NUM, userEntity.diamond);
            bundle.putInt(LimitAnswerActivity.KEY_ANSWER_BATCH, batchInfoEntity.batch);
        }
        intent.putExtras(bundle);
        startActivity(intent);
        this.finish();
    }

    /**
     * 计算分数占比
     *
     * @param scores
     * @return
     */
    private float[] caculatorPrecent(List<Integer> scores) {
        if (scores == null) {
            return new float[4];

        }
        int total = 0;
        for (int score : scores) {
            total += score;
        }
        float[] precents = new float[4];
        if (total == 0) {
            for (int i = 0; i < scores.size(); i++) {
                precents[i] = 0.25f * 0.2f;
            }
        } else {
            for (int i = 0; i < scores.size(); i++) {
                precents[i] = scores.get(i) / total * 0.2f;
            }
        }
        precents[chioicePos] = precents[chioicePos] + 0.8f;
        return precents;
    }

    /**
     * 筛选好友
     * 推荐好友》圈一圈好友》通讯录好友
     */
    private void loadFriends() {
        if (contactsFlag && recommendFlag && qyqFriendFlag) {
            view_circle_friend.setOnSelectedItemListener(AnswerSubjectActivity.this);
            view_circle_friend.setAvaliableSelected(true);
            if (friendEntities == null || friendEntities.size() < 4) {
                friendEntities.clear();
                friendEntities.addAll(FriendManager.getSubjectCandidate(recommendFriend, qyqFriendList, contactsInfoEntities, maxNum));
                if (friendEntities.size() < 4) {
                    Toast.makeText(AnswerSubjectActivity.this, "好友人数少于4人，请先添加好友", Toast.LENGTH_SHORT).show();
//                    startActivity(new Intent(AnswerSubjectActivity.this, AddContactsFriendActivity.class));
                    toMainActivity(MainActivity.POSITION_FRIEND);
                    finish();
                } else {
                    changeCircleFriend();
                }
            } else {
                getFirstShowFriend(subjectsEntities.get(mSubjectProgess));
            }
        } else {
            view_circle_friend.setOnSelectedItemListener(null);
            view_circle_friend.setAvaliableSelected(false);
        }

    }

    private float downY;
    private float upY;

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (showCandidate) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                downY = event.getY();
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                upY = event.getY();
                if (downY - upY > 100) {
                    showSetCandidateDialog();
                    return true;
                } else if (upY - downY > 100) {
                    if (setCandidateDialog != null
                            && setCandidateDialog.isShowing()) {
                        setCandidateDialog.dismiss();
                        return true;
                    }
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public void onEventMainThread(BaseMessageEvent event) {
        super.onEventMainThread(event);
        if (event != null && event.eventId == EventManager.EVENT_UPDATE_USERINFO) {
            userEntity = UserManager.getUesrInfo(this);
            if (userEntity != null) {
                text_hot_num.setText(userEntity.diamond + "");
            }
        }
    }

    /**
     * 详情页的分享按钮
     */
    @OnClick(R.id.view_share)
    public void clickShare() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            startActivityForResult(new Intent(this, ScreenShotActivity.class),
                    ScreenShotActivity.REQUEST_MEDIA_PROJECTION);
        } else {
            shotterView();
        }
    }

    /**
     * 答题时的分享按钮
     */
    @OnClick(R.id.text_answer_share)
    public void clickAnswerShare() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            startActivityForResult(new Intent(this, ScreenShotActivity.class),
                    ScreenShotActivity.REQUEST_MEDIA_PROJECTION);
        } else {
            shotterView();
        }
    }


    /**
     * 低于6.0版本使用该方法截图
     */
    private void shotterView() {
        View decorView = getWindow().getDecorView();
        decorView.destroyDrawingCache();
        decorView.setDrawingCacheEnabled(true);
        decorView.buildDrawingCache();
        Bitmap bitmap = decorView.getDrawingCache();
        showShareDialog(bitmap);
    }

    private void showShareDialog(String bitmapUrl) {
        if (shareAnswerDetailDialog == null) {
            shareAnswerDetailDialog = new ShareAnswerDetailDialog(this);
        }
        shareAnswerDetailDialog.showShortView(bitmapUrl);
        shareAnswerDetailDialog.show();
    }

    private void showShareDialog(Bitmap bitmap) {
        if (shareAnswerDetailDialog == null) {
            shareAnswerDetailDialog = new ShareAnswerDetailDialog(this);
        }
        shareAnswerDetailDialog.showShortView(bitmap);
        shareAnswerDetailDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ScreenShotActivity.REQUEST_MEDIA_PROJECTION
                && resultCode == Activity.RESULT_OK) {
            final ShotterManager shotter = new ShotterManager(AnswerSubjectActivity.this, data);
            if (friendCircleInfoEntity != null) {
                shotUrl = ShotterManager.mPath + "/" + friendCircleInfoEntity.recordId + ".png";
            } else if (subjectsEntity != null) {
                shotUrl = ShotterManager.mPath + "/" + subjectsEntity.subId + ".png";
            }
            shotter.startScreenShot(new ShotterManager.OnShotListener() {
                @Override
                public void onFinish() {
                    showShareDialog(shotUrl);
                }
            }, shotUrl);
        }
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void updateSubjectsView(AnswerEntity answerEntity) {
        //更新题目资源
        if (answerEntity != null) {
            this.answerEntity = answerEntity;
            unlockcost = answerEntity.unlockcost;
            subjectSize = answerEntity.subjects.size();
            mExpire = answerEntity.expire;
            if (answerEntity.expire > 0 || answerEntity.expire < 0 || answerEntity.subjects.size() == 0) {
                toLimitView(answerEntity.batchInfo);
                return;
            } else {
                recommendFlag = true;
                setData(answerEntity);
                showSubjectView();
                List<MineFriendEntity> recommends = new ArrayList<>();
                recommends.addAll(recommendFriend);
                friendEntities.clear();
                friendEntities.addAll(FriendManager.mergeFriends(recommends, subjectRecommend, maxNum));
                if (friendEntities.size() > 4) {
                    view_circle_friend.setOnSelectedItemListener(AnswerSubjectActivity.this);
                    view_circle_friend.setAvaliableSelected(true);
//                    getFirstShowFriend(subjectsEntities.get(mSubjectProgess));
                }
                loadFriends();
            }
        }
        canAnswer = true;
    }


    @Override
    public void updateAnswerSubject(NetworkManager.ResultCode resultCode,
                                    AnswerResultEntity answerResultEntity) {
        if (setCandidateDialog != null) {
            setCandidateDialog.dismiss();
        }
        //答题后的操作
        if (resultCode.equals(NetworkManager.ResultCode.RESULT_SUCCESS)) {
            mExpire = answerResultEntity.expire;
            String message = answerResultEntity.scores;
            unlockcost = answerResultEntity.unlockcost;
//            if (expireTime > 0) {
//                toLimitView(batchInfoEntity, expireTime);
//            } else {
            //答完题需要点击下一题才可以换题
            mSubjectProgess++;//下一题的序列号
            if (note_type == 1) {
                List<Integer> scores = JSON.parseArray(message, Integer.class);
                float[] percents = caculatorPrecent(scores);
                view_circle_friend.showChoicePercent(percents, mColor);
            } else if (note_type == 0) {
                //换题才可以重置好友圈选的点击事件
                view_circle_friend.setOnSelectedItemListener(this);
                view_circle_friend.setAvaliableSelected(true);
                showNextSubject();
            }
        }
//        }
    }

    @Override
    public void updateDetailView(MsgInfoEntity msgInfoEntity, SubjectsEntity subjectsEntity) {
        showSubjectDetail(msgInfoEntity, subjectsEntity);
    }

    @Override
    public void updateLockDetailView(NetworkManager.ResultCode resultCode, String text) {
        presenter.loadDetailInfoData(recordId, mType);
    }


    @Override
    public void updateFriendListView(List<MineFriendEntity> friendEntityList) {
        //获取通讯录好友
        qyqFriendList.clear();
        qyqFriendList.addAll(friendEntityList);
        qyqFriendFlag = true;
        loadFriends();
    }

    @Override
    public void updateSetCandidateView(CommonEntity commonEntity) {
        //更新设置候选人后的列表
        Toast.makeText(this, "设置成功！", Toast.LENGTH_SHORT).show();
        if (setCandidateDialog != null) {
            setCandidateDialog.dismiss();
        }
        recommendFriend.clear();
        recommendFriend.addAll(setCandidateDialog.getSelectedFriends());
//        loadFriends();
        changeFirendAfterSetCandidate();
        canAnswer = true;
    }

}
